#include "cmsis_os2.h"
#include <stdio.h>
#include <string.h>

#define TASK_PRIO_TEST    osPriorityNormal
#define STACK_SIZE        1024  // 可按需修改
#define TICK_MS           1     // 假设 1 tick = 1ms

osThreadId_t g_testTaskId01;
osThreadId_t g_testTaskId02;
osSemaphoreId_t g_semId;

void Example_SemTask1(void *argument)
{
    osStatus_t status;

    printf("Example_SemTask1 try get sem g_semId, timeout 10 ticks.\n");

    status = osSemaphoreAcquire(g_semId, 10 * TICK_MS);
    if (status == osOK) {
        printf("Example_SemTask1 got semaphore.\n");
        osSemaphoreRelease(g_semId);
        return;
    }

    if (status == osErrorTimeout) {
        printf("Example_SemTask1 timeout, try wait forever.\n");
        status = osSemaphoreAcquire(g_semId, osWaitForever);
        if (status == osOK) {
            printf("Example_SemTask1 acquired semaphore after wait_forever.\n");
            osSemaphoreRelease(g_semId);
        }
    }
}

void Example_SemTask2(void *argument)
{
    osStatus_t status;

    printf("Example_SemTask2 try get sem g_semId wait forever.\n");
    status = osSemaphoreAcquire(g_semId, osWaitForever);
    if (status == osOK) {
        printf("Example_SemTask2 got sem, now delaying 20 ticks.\n");
        osDelay(20 * TICK_MS);
        printf("Example_SemTask2 releasing sem.\n");
        osSemaphoreRelease(g_semId);
    }
}

int main(void)
{
    osKernelInitialize();

    // 创建信号量，最大值=1，初始值=0
    g_semId = osSemaphoreNew(1, 0, NULL);
    if (g_semId == NULL) {
        printf("Semaphore creation failed.\n");
        return -1;
    }

    // 创建任务1
    const osThreadAttr_t task1Attr = {
        .name = "TestTask1",
        .priority = TASK_PRIO_TEST,
        .stack_size = STACK_SIZE
    };
    g_testTaskId01 = osThreadNew(Example_SemTask1, NULL, &task1Attr);
    if (g_testTaskId01 == NULL) {
        printf("Task1 creation failed.\n");
        return -1;
    }

    // 创建任务2
    const osThreadAttr_t task2Attr = {
        .name = "TestTask2",
        .priority = TASK_PRIO_TEST - 1,
        .stack_size = STACK_SIZE
    };
    g_testTaskId02 = osThreadNew(Example_SemTask2, NULL, &task2Attr);
    if (g_testTaskId02 == NULL) {
        printf("Task2 creation failed.\n");
        return -1;
    }

    osSemaphoreRelease(g_semId);  // 启动时释放1次信号量
    osKernelStart();              // 启动调度器

    // 后续的延时、删除任务等操作若需保留，可在一个后台任务里处理
    return 0;
}